package com.horse.cloud.framework.general.utils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.StringUtils;

import java.beans.BeanInfo;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.HashMap;
import java.util.Map;

/**
 * @create : Created by intelliJ IDEA 16.1.3
 * @author : bing.Pan
 * @e-mail : 15923508369@163.com
 * @gmdate : 2017/6/3 14:04
 * @sidesc :
 */
public class BeanMapUtils {
    private static Logger LOGGER =  LoggerFactory.getLogger(BeanMapUtils.class);

    /**
     * 对象转map
     * @param obj
     * @return
     */
    public static Map<String, Object> beanTrans2Map(Object obj) {

        if (StringUtils.isEmpty(obj)){
            return null;
        }

        try {
            BeanInfo beanInfo = Introspector.getBeanInfo(obj.getClass());
            PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
            Map<String, Object> map = new HashMap<>();
            for (PropertyDescriptor property : propertyDescriptors) {
                String key = property.getName();
                if (!key.equals("class")) {
                    Method getter = property.getReadMethod();
                    Object value = getter.invoke(obj);

                    map.put(key, value);
                }
            }
            return map;
        } catch (Exception e) {
            LOGGER.info("【framework】 对象转map发生异常");
        }
        return null;
    }


    /**
     * map 转Java bean
     * @param map
     * @param beanClass
     * @param <T>
     * @return
     * @throws Exception
     */
    public static  <T> T mapTransBean(Map<String, String> map, Class<T> beanClass) {

        try{
            if (map == null){
                return null;
            }

            T obj = beanClass.newInstance();

            Field[] fields = obj.getClass().getDeclaredFields();
            for (Field field : fields) {
                int mod = field.getModifiers();
                if(Modifier.isStatic(mod) || Modifier.isFinal(mod)){
                    continue;
                }

                field.setAccessible(true);
                field.set(obj, map.get(field.getName()));
            }
            return obj;
        }catch (Exception exception){
            LOGGER.info("【framework】 map 转对象时发生异常");
        }

        return null;
    }
}
